package binarytree

import (
	"strconv"
	"strings"
)

type Codec struct {
}

func Constructor297() Codec {
	return Codec{}
}

// Serializes a tree to a single string.
func (this *Codec) serialize(root *TreeNode) string {
	res := &strings.Builder{}
	var dfs func(*TreeNode)
	dfs = func(root *TreeNode) {
		if root == nil {
			res.WriteString("null,")
			return
		}
		res.WriteString(strconv.Itoa(root.Val))
		res.WriteString(",")
		dfs(root.Left)
		dfs(root.Right)
	}

	dfs(root)
	return res.String()
}

// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {
	val_list := strings.Split(data, ",")
	var build func() *TreeNode
	build = func() *TreeNode {
		if val_list[0] == "null" {
			val_list = val_list[1:]
			return nil
		}
		val, _ := strconv.Atoi(val_list[0])
		val_list = val_list[1:]
		return &TreeNode{val, build(), build()}
	}
	return build()
}
